package thread;


import java.util.Comparator;
import java.util.PriorityQueue;

//有个任务类
/*class MyTimerTask implements Runnable {

    Runnable task;
    int time;

    public MyTimerTask(Runnable task, long delay) {
        this.task = task;
        time = (int) (System.currentTimeMillis() + delay);
    }

    public int getTime() {
        //获取执行任务的时刻
        return time;
    }

    @Override
    public void run() {
        task.run();
    }

}
class Mytimer {
    private static Object locker = new Object();
    //使用小根堆来存储任务---可以更加方便的去判断任务是否达到执行时机  只看堆顶元素 如果堆顶都没到 那后面的就不用说 肯定也没到
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<MyTimerTask>(new Comparator<MyTimerTask>() {
        @Override
        public int compare(MyTimerTask o1, MyTimerTask o2) {
            return o1.getTime() - o2.getTime();
        }
    });

    public void schedule(Runnable task, long delay) {
        synchronized (locker) {
            queue.add(new MyTimerTask(task, delay));
            locker.notifyAll();
        }
    }
    public Mytimer() {
        Thread t = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    MyTimerTask task = queue.peek();
                  *//*  while (task == null) {
                        try {
                            //避免无意义的循环判断导致 资源消耗 线程饿死
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }*//*

                        task = queue.peek();//二次判断 处理wait被异常情况唤醒的情况
                    }
                    if (task.getTime() <= System.currentTimeMillis()) {
                        //时间到了或者超了
                        //执行任务
                        task.run();
                        queue.poll();
                    } else {
                        //此处也要规避无意义循环
                        //时间没到
                        try {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }

            }
        });
        t.start();
    }
    //创建线程去执行这个些任务
}*/
/*
public class demo34 {
    public static void main(String[] args) {
        Mytimer mytimer = new Mytimer();
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
    }

}
*/
